from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy.orm import Session
from app.core.security import create_token
from app.core.config import settings
from app.db.session import get_db
from app.models.user import User
from app.utils.wechat import WeChatAPI
from app.schemas.auth import WechatLogin, Token
from app.core.logging_config import get_logger

logger = get_logger(__name__)
router = APIRouter()

@router.post("/wechat-login", response_model=Token)
async def wechat_login(
    login_data: WechatLogin,
    db: Session = Depends(get_db)
):
    """微信一键登录"""
    try:
        # 获取微信用户信息
        wx_data = WeChatAPI.code2session(login_data.code)
        if not wx_data:
            logger.error("Failed to get WeChat user info")
            raise HTTPException(status_code=400, detail="获取微信用户信息失败")
            
        openid = wx_data.get("openid")
        if not openid:
            logger.error("No openid in WeChat response")
            raise HTTPException(status_code=400, detail="获取openid失败")
            
        logger.info(f"WeChat login attempt with openid: {openid}")
        
        # 查找或创建用户
        user = db.query(User).filter(User.openid == openid).first()
        if not user:
            # 创建新用户
            user = User(
                openid=openid,
                nickname=f"用户_{openid[:8]}",  # 默认昵称
                is_active=True
            )
            db.add(user)
            db.commit()
            db.refresh(user)
            logger.info(f"Created new user: {user.id}")
        
        # 创建访问令牌
        access_token = create_token(
            data={"sub": str(user.id)},
            expires_delta=settings.ACCESS_TOKEN_EXPIRE_MINUTES
        )
        
        logger.info(f"Login successful for user: {user.id}")
        return {
            "access_token": access_token,
            "token_type": "bearer",
            "user_info": {
                "id": user.id,
                "nickname": user.nickname,
                "avatar": user.avatar
            }
        }
        
    except Exception as e:
        logger.exception("Login failed")
        raise HTTPException(status_code=500, detail="登录失败，请稍后重试") 